#import('dart:io');
#import('dart:json');

final IP = '127.0.0.1';
final PORT = 8080;

Map<String, Client> connections;

class Client {
  int token;
  WebSocketConnection conn;
  Map icons;
  
  Client(this.token, this.conn, this.icons) {
    conn.onMessage = (message) {
      print("Client.conn.onMessage=${message}");
      connections.forEach((k,v) {
        if (conn != v.conn) v.conn.send(message);
      });
    };
    
    conn.onClosed = (int status, String reason) {
      print("Client.conn.onClosed status=${status},reason=${reason}");
      connections.remove(token.toString());
    };
          
    conn.onError = (e) {
      print("Client.conn.onError e=${e}");
      connections.remove(token.toString());
    };
    
    Map cmdMap = new Map();
    cmdMap["setName"] = "BB-${token}";
    conn.send(JSON.stringify(cmdMap));
    
    cmdMap = new Map();
    cmdMap["setIcons"] = icons;
    conn.send(JSON.stringify(cmdMap));
  }
  
  String toString() {
    return token.toString();
  }
}

void main() {
  int token = 0;
  connections = new Map();
  
  HttpServer server = new HttpServer();
  WebSocketHandler wsHandler = new WebSocketHandler();
  server.addRequestHandler((req) => req.path == "/bbws", wsHandler.onRequest);

  String imgDir = "images";
  Map icons = {
        "Alien" : "${imgDir}/alien.png",
        "AngryBird" : "${imgDir}/angrybird.png",
        "Cake" : "${imgDir}/cake.png",
        "Robot" : "${imgDir}/robot.png",
        "Smiley" : "${imgDir}/smiley.png",
        "Spaceship" : "${imgDir}/spaceship.png"};
  
  List staticFiles = ["bb_client.html", "bb_client.dart", "bb_client.dart.js", "bb_client.dart.js_", "dart.js"];
  icons.forEach((n, f) {staticFiles.add("${f}"); });

  print(staticFiles);
  
  server.addRequestHandler((req) => req.path == "/", (HttpRequest req, HttpResponse res) {
    print(req.path);
    File file = new File(staticFiles[0]); 
    file.openInputStream().pipe(res.outputStream); 
  });
  
  staticFiles.forEach((f) {
    server.addRequestHandler((req) => req.path == "/${f}", (HttpRequest req, HttpResponse res) {
      print(req.path);
      File file = new File(f); 
      file.openInputStream().pipe(res.outputStream); 
    });
  });
  
  wsHandler.onOpen = (WebSocketConnection conn) {
    print("client.conn.onOpen conn=${conn.toString()}");
    token++;
    var c = new Client(token, conn, icons);
    print("adding Client connection token = ${token}");
    connections[token.toString()] = c;
  };
  
  print('listing on http://$IP:$PORT');
  server.listen(IP, PORT);
} 